from flask import Blueprint, redirect, session, render_template, url_for, request, g
import os
from .forms import QuestionForm, AnswerForm, ChatForm
from models import QuestionModel, AnswerModel, ChatModel
from exts import db
from decorators import login_required

bp = Blueprint('qa', __name__, url_prefix='/')


@bp.route('/')
def index():
    questions = QuestionModel.query.order_by(QuestionModel.join_time.desc()).all()
    return render_template('index.html', questions=questions)


@bp.route('/qa/public', methods=['GET', 'POST'])
@login_required
def public():
    if request.method == 'GET':
        return render_template('public_question.html')
    else:
        form = QuestionForm(request.form)
        if form.validate():
            title = form.title.data
            content = form.content.data
            price = form.price.data
            file = request.files['img-file']
            if file:
                try:
                    filename = file.filename
                    # file.save(os.path.join(f'/to/your/path/static/images/goods/{filename}'))
                    file.save(os.path.join(f'E:/Py_test/My_web/static/images/goods/{filename}'))
                except:
                    return '图片保存失败'
            else:
                pass
            question = QuestionModel(title=title, content=content, price=price, filename=file.filename, author=g.user)
            db.session.add(question)
            db.session.commit()
            return redirect('/')
        else:
            list_pub = []
            for error in form.errors.values():
                list_pub.append(error[0])
            return ', '.join(list_pub)


@bp.route('/qa/detail/<qa_id>')
def detail(qa_id):
    question = QuestionModel.query.get(qa_id)
    return render_template('detail.html', question=question)


@bp.post('/answer/public')
@login_required
def public_ans():
    form = AnswerForm(request.form)
    if form.validate():
        content = form.content.data
        question_id = form.question_id.data
        answer = AnswerModel(content=content, question_id=question_id, author_id=g.user.id)
        db.session.add(answer)
        db.session.commit()
        return redirect(url_for('qa.detail', qa_id=question_id))
    else:
        list_ans = []
        for error in form.errors.values():
            list_ans.append(error[0])
        return ', '.join(list_ans)


@bp.route('/search')
@login_required
def search():
    q = request.args.get('q')
    questions = QuestionModel.query.filter(QuestionModel.title.contains(q)).all()
    return render_template('index.html', questions=questions)


@bp.route('/chat', methods=['GET', 'POST'])
@login_required
def chat():
    if request.method == 'GET':
        chats = ChatModel.query.order_by(ChatModel.join_time).all()
        return render_template('chat.html', chats=chats)
    elif request.method == 'POST':
        form = ChatForm(request.form)
        if form.validate():
            content = request.form.get('content')
            chat = ChatModel(content=content, author_id=g.user.id)
            db.session.add(chat)
            db.session.commit()
            return redirect(url_for('qa.chat'))
        else:
            list_ans = []
            for error in form.errors.values():
                list_ans.append(error[0])
            return ', '.join(list_ans)


@bp.route('/images/<filename>')
@login_required
def img(filename):
    return render_template('image.html', filename=filename)


@bp.route('/confirm/<qa_id>', methods=['GET', 'POST'])
@login_required
def confirm(qa_id):
    if request.method == 'GET':
        return render_template('confirm.html')
    elif request.method == 'POST':
        if request.form.get('placeconfirm') == 'your postal code':
            question = QuestionModel.query.get(qa_id)
            return render_template('email.html', question=question)
        else:
            return '验证失败'
